<?php

namespace App\Http\Controllers\Api\CMS;

use App\Http\Requests\ContentPictureRequest;
use App\Http\Resources\ContentPictureResource;
use App\Models\CMS\Category;
use App\Models\CMS\Content;
use App\Models\CMS\Picture;
use App\Services\CmsService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ContentPictureController extends Controller
{
    /**
     * 构造方法
     * @var CmsService
     */
    public $cmsService;

    public function __construct()
    {
        $this->cmsService = new CmsService();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $keyword = $request->get('keyword', '');
        $category_id = $request->get('category_id', []);
        $models = Picture::query()->when($category_id, function ($query) use ($category_id) {
            return $query->whereHas('contents.categorylabel', function ($q) use ($category_id) {
                foreach ($category_id as $item) {
                    $q->where('category_path', 'like', "%{$item}%");
                }
            });
        })->when($keyword, function ($query) use ($keyword) {
            $query->whereHas('contents.category', function ($q) use ($keyword) {
                $q->where('name', 'like', '%' . $keyword . '%');
            })->orWhereHas('contents', function ($q) use ($keyword) {
                $q->where('title', 'like', '%' . $keyword . '%');
            });
        })->with('contents.category', 'contents.categorylabel', 'contents')->orderByDesc('cms_content_pictures.id')->paginate();
        return ContentPictureResource::collection($models);
    }

    /**
     * @param Request $request
     * @return ContentPictureResource
     */
    public function store(Request $request)
    {
        $data = $request->all();
        $columns = $this->syncColumns($data['category']);
        $validator = $this->validateData($data);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }
        DB::beginTransaction();
        try {
            $content = new Content();
            $content->fill($data);
            $content->content_detail_type = 'ContentPicture';
            $content->content_detail_id = 0;
            $content->status = 1;
            $tags = $data['tags'];
            $this->cmsService->asyncTags($tags);
            $content->tags = json_encode($tags);
            $content->view_count = $content->view_count ? $content->view_count : 0;
            $content->save();
            $contentPicture = new Picture();
            $contentPicture->fill($data);
            if ($data['point_category_id']) {
                $contentPicture->point_category_id = end($data['point_category_id']);
                $contentPicture->point_category_path = implode("-", $data['point_category_id']);
            }
            $contentPicture = $this->fillData($data, $contentPicture);
            $contentPicture->content_id = $content->id;
            $contentPicture->save();
            $content->content_detail_id = $contentPicture->id;
            $content->save();
            $content->category()->sync($columns);
            DB::commit();
            return new ContentPictureResource($contentPicture);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json($e->getMessage(), 422);
        }
    }

    /**
     * 格式化栏目参数
     * @param $column
     * @return array
     */
    protected function syncColumns($column)
    {
        $arr = [];
        foreach ($column as $item) {
            if ($item) {
                $arr[end($item)] = ['category_path' => '-' . implode("-", $item) . '-'];
            }
        }
        return $arr;
    }

    /**
     * @param $cpId
     * @return ContentPictureResource
     */
    public function show($cpId)
    {
        $model = $this->findModel($cpId);
        return new ContentPictureResource($model);
    }

    /**
     * @param Request $request
     * @param $cpId
     * @return ContentPictureResource
     */
    public function update(Request $request, $cpId)
    {
        $data = $request->all();
        $columns = $this->syncColumns($data['category']);
        $validator = $this->validateData($data);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }
        DB::beginTransaction();
        try {
            $contentPicture = $this->findModel($cpId);
            $content = $contentPicture->contents;
            $content->fill($data);
            $tags = $data['tags'];
            $this->cmsService->asyncTags($tags);
            $content->tags = json_encode($tags);
            $content->save();
            $contentPicture->fill($data);
            if ($data['point_category_id']) {
                $contentPicture->point_category_id = end($data['point_category_id']);
                $contentPicture->point_category_path = implode("-", $data['point_category_id']);
            }
            $contentPicture->save();
            $content->save();
            $content->category()->sync($columns);
            DB::commit();
            return new ContentPictureResource($contentPicture);
            return response()->json('添加成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json($e->getMessage(), 422);
        }
    }

    /**
     * @param $cpId
     * @return array
     * @throws \Exception
     */
    public function destroy($cpId)
    {
        $model = ContentPicture::query()->where('id', $cpId)->first();
        $content = $model->contents;
        $content->delete();
        $model->delete();
        return response()->json(['删除成功']);
    }

    protected function findModel($cpId)
    {
        $model = Picture::query()->with('contents.category', 'contents.categorylabel','asset')->where('id', $cpId)->first();
        return $model;
    }

    protected function getCategoryIdStr($categoryIdArr)
    {

        return implode(',', $categoryIdArr);
    }


    public function validateData($data)
    {
        $valid = Validator::make($data, [], [
            'point_category_id.exists' => '指向分类必填',
            'point_content_id.exists' => '内容必填',
            'point_url.required' => 'Url必填',
        ]);
        $valid->sometimes('point_category_id', 'exists:cms_categories,id', function ($input) {
            return in_array($input->point_type, [1, 2]);
        });
        $valid->sometimes('point_content_id', 'exists:cms_contents,id', function ($input) {
            return $input->point_type == 1;
        });
        $valid->sometimes('point_url', 'required', function ($input) {
            return $input->point_type == 3;
        });

        return $valid;
    }

    public function fillData($data, $model)
    {
        switch ($data['point_type']) {
            case 1:
                $model->point_url = 'content/' . $data['point_content_id'];
                break;
            case 2:
                $model->point_url = 'list/' . end($data['point_category_id']);
                break;
            case 3:
            default :
                $model->point_url = $data['point_url'];
        };
        return $model;
    }
}
